package com.css.zfzx.sjcj.modules.hddcB4_SampleDataTable.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB4_SampleDataTable.repository.HddcB4SampledatatableNativeRepository;
import com.css.zfzx.sjcj.modules.hddcB4_SampleDataTable.repository.HddcB4SampledatatableRepository;
import com.css.zfzx.sjcj.modules.hddcB4_SampleDataTable.repository.entity.HddcB4SampledatatableEntity;
import com.css.zfzx.sjcj.modules.hddcB4_SampleDataTable.service.HddcB4SampledatatableService;
import com.css.zfzx.sjcj.modules.hddcB4_SampleDataTable.viewobjects.HddcB4SampledatatablePageVO;
import com.css.zfzx.sjcj.modules.hddcB4_SampleDataTable.viewobjects.HddcB4SampledatatableQueryParams;
import com.css.zfzx.sjcj.modules.hddcB4_SampleDataTable.viewobjects.HddcB4SampledatatableVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 野外采样数据-样品数据表管理
 * @author zhangcong
 * @date 2020-11-30
 */
@Service
public class HddcB4SampledatatableServiceImpl implements HddcB4SampledatatableService {

    private final HddcB4SampledatatableRepository hddcB4SampledatatableRepository;
    private final HddcB4SampledatatableNativeRepository hddcB4SampledatatableNativeRepository;
    private final FieldSamplingDataTableExcelVerifyHandler fieldSamplingDataTableExcelVerifyHandler;

    @Autowired
    public HddcB4SampledatatableServiceImpl(HddcB4SampledatatableRepository hddcB4SampledatatableRepository,
                                            HddcB4SampledatatableNativeRepository hddcB4SampledatatableNativeRepository,
                                            FieldSamplingDataTableExcelVerifyHandler fieldSamplingDataTableExcelVerifyHandler) {
        this.hddcB4SampledatatableRepository = hddcB4SampledatatableRepository;
        this.hddcB4SampledatatableNativeRepository = hddcB4SampledatatableNativeRepository;
        this.fieldSamplingDataTableExcelVerifyHandler = fieldSamplingDataTableExcelVerifyHandler;
    }

    @Override
    public JSONObject queryHddcB4Sampledatatables(HddcB4SampledatatableQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcB4SampledatatablePageVO> hddcB4SampledatatablePage = this.hddcB4SampledatatableNativeRepository.queryHddcB4Sampledatatables(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcB4SampledatatablePage);
    }


    @Override
    public HddcB4SampledatatableEntity getHddcB4Sampledatatable(String id) {
        return this.hddcB4SampledatatableRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB4SampledatatableEntity saveHddcB4Sampledatatable(HddcB4SampledatatableEntity hddcB4Sampledatatable) {
        String uuid = UUIDGenerator.getUUID();
        hddcB4Sampledatatable.setUuid(uuid);
        hddcB4Sampledatatable.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcB4Sampledatatable.setCreateTime(now);
        hddcB4Sampledatatable.setUpdateTime(now);
        hddcB4Sampledatatable.setIsValid(PlatformConstants.Y);
        hddcB4Sampledatatable.setQualityinspectionStatus(PlatformConstants.N);
        hddcB4Sampledatatable.setExtends10(PlatformConstants.Y);
        this.hddcB4SampledatatableRepository.save(hddcB4Sampledatatable);
        return hddcB4Sampledatatable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB4SampledatatableEntity updateHddcB4Sampledatatable(HddcB4SampledatatableEntity hddcB4Sampledatatable) {
        HddcB4SampledatatableEntity entity = hddcB4SampledatatableRepository.findById(hddcB4Sampledatatable.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcB4Sampledatatable);
        hddcB4Sampledatatable.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcB4Sampledatatable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcB4SampledatatableRepository.save(hddcB4Sampledatatable);
        return hddcB4Sampledatatable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcB4Sampledatatables(List<String> ids) {
        List<HddcB4SampledatatableEntity> hddcB4SampledatatableList = this.hddcB4SampledatatableRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcB4SampledatatableList) && hddcB4SampledatatableList.size() > 0) {
            for(HddcB4SampledatatableEntity hddcB4Sampledatatable : hddcB4SampledatatableList) {
//                this.hddcB4SampledatatableRepository.delete(hddcB4Sampledatatable);
                hddcB4Sampledatatable.setIsValid(PlatformConstants.N);
                hddcB4Sampledatatable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcB4Sampledatatable.setUpdateTime(new Date());
                this.hddcB4SampledatatableRepository.save(hddcB4Sampledatatable);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcB4SampledatatableQueryParams queryParams, HttpServletResponse response) {
        List<HddcB4SampledatatableEntity> yhDisasterEntities = hddcB4SampledatatableNativeRepository.exportYhDisasters(queryParams);
        List<HddcB4SampledatatableVO> list=new ArrayList<>();
        for (HddcB4SampledatatableEntity entity:yhDisasterEntities) {
            HddcB4SampledatatableVO yhDisasterVO=new HddcB4SampledatatableVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"样品数据表","样品数据表",HddcB4SampledatatableVO.class,"样品数据表.xls",response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(fieldSamplingDataTableExcelVerifyHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcB4SampledatatableVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcB4SampledatatableVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcB4SampledatatableVO yhDisasterVO : result.getFailList()) {
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                }
            }
            List<HddcB4SampledatatableVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     */
    public void saveDisasterList(List<HddcB4SampledatatableVO> list) {
        for (HddcB4SampledatatableVO hddcB4SampledatatableVO : list) {
            HddcB4SampledatatableEntity yhDisasterEntity = new HddcB4SampledatatableEntity();
            BeanUtils.copyProperties(hddcB4SampledatatableVO, yhDisasterEntity);
            saveHddcB4Sampledatatable(yhDisasterEntity);
        }
    }
    /**
     * 逻辑删除-根据项目id删除数据
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcB4SampledatatableEntity> hddcDataList = this.hddcB4SampledatatableRepository.queryByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcDataList) && hddcDataList.size() > 0) {
            for(HddcB4SampledatatableEntity entity : hddcDataList) {
                entity.setUpdateUser(PlatformSessionUtils.getUserId());
                entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                entity.setIsValid(PlatformConstants.N);
                this.hddcB4SampledatatableRepository.save(entity);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcB4SampledatatableEntity> hddcDataList = this.hddcB4SampledatatableRepository.queryByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcDataList) && hddcDataList.size() > 0) {
            for(HddcB4SampledatatableEntity entity : hddcDataList) {
                entity.setUpdateUser(PlatformSessionUtils.getUserId());
                entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                entity.setIsValid(PlatformConstants.N);
                this.hddcB4SampledatatableRepository.save(entity);
            }
        }
    }
}
